package com.caseprocessing.ai;

import com.caseprocessing.api.*;
import com.caseprocessing.config.AIConfig;
import com.caseprocessing.model.CaseDocument;
import com.caseprocessing.model.DocumentSegment;
import com.caseprocessing.model.DocumentType;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * AI服务管理器
 * 协调LLM和VLM的使用，提供统一的AI增强服务
 */
public class AIServiceManager {
    
    private final SiliconFlowClient siliconFlowClient;
    private final AIPromptLibrary promptLibrary;
    private final AIConfig config;
    private final Map<String, Object> serviceConfig;
    
    public AIServiceManager(String apiKey) {
        this.config = AIConfig.getInstance();
        this.siliconFlowClient = new SiliconFlowClient(apiKey);
        this.promptLibrary = new AIPromptLibrary();
        this.serviceConfig = new HashMap<>();
        
        // 从配置文件加载配置
        serviceConfig.put("default_temperature", config.getLlmTemperature());
        serviceConfig.put("max_tokens", config.getLlmMaxTokens());
        serviceConfig.put("timeout_seconds", config.getProcessingTimeout());
        
        if (config.isApiLogsEnabled()) {
            System.out.println("🤖 AI服务管理器初始化完成");
        }
    }
    
    /**
     * 使用配置文件中的API密钥创建服务管理器
     */
    public AIServiceManager() {
        this(null);
    }
    
    /**
     * AI增强的文档分割
     * 结合VLM视觉分析和LLM语义理解
     */
    public CompletableFuture<List<DocumentSegment>> aiEnhancedDocumentSplit(
            CaseDocument caseDocument, 
            List<String> documentImages) {
        
        // 1. 使用VLM分析文档视觉结构
        CompletableFuture<DocumentAnalysisResult> visionAnalysis = 
            analyzeDocumentStructure(caseDocument, documentImages);
        
        // 2. 使用LLM分析文档语义结构
        CompletableFuture<DocumentAnalysisResult> semanticAnalysis = 
            analyzeDocumentSemantics(caseDocument);
        
        // 3. 融合分析结果，生成分割策略
        return CompletableFuture.allOf(visionAnalysis, semanticAnalysis)
                .thenCompose(v -> {
                    try {
                        DocumentAnalysisResult vision = visionAnalysis.get();
                        DocumentAnalysisResult semantic = semanticAnalysis.get();
                        
                        return generateSplitStrategy(caseDocument, vision, semantic);
                    } catch (Exception e) {
                        throw new RuntimeException("AI分析失败", e);
                    }
                });
    }
    
    /**
     * AI增强的文档分类
     * 零样本学习，适应新文书类型
     */
    public CompletableFuture<DocumentType> aiEnhancedDocumentClassification(
            DocumentSegment segment, 
            List<String> segmentImages) {
        
        String prompt = promptLibrary.getClassificationPrompt();
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请分析以下文档内容并进行分类：\\n" + segment.getContent())
                .build()
        );
        
        CompletableFuture<ChatCompletionResponse> response;
        
        if (segmentImages != null && !segmentImages.isEmpty()) {
            // 使用VLM进行多模态分类
            response = siliconFlowClient.chatCompletionVLM(
                messages, 
                segmentImages, 
                ChatCompletionRequest.builder()
                    .temperature(0.1)
                    .maxTokens(1000)
            );
        } else {
            // 使用LLM进行文本分类
            response = siliconFlowClient.chatCompletionLLM(
                messages, 
                ChatCompletionRequest.builder()
                    .temperature(0.1)
                    .maxTokens(1000)
            );
        }
        
        return response.thenApply(this::parseClassificationResult);
    }
    
    /**
     * AI增强的合规性检查
     * 深度理解法规要求，提供详细的改进建议
     */
    public CompletableFuture<DocumentAnalysisResult> aiEnhancedComplianceCheck(
            DocumentSegment segment, 
            DocumentType documentType, 
            List<String> segmentImages) {
        
        String prompt = promptLibrary.getComplianceCheckPrompt(documentType);
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(prompt)
                .build(),
            Message.builder()
                .role("user")
                .content("请检查以下" + documentType.getDescription() + "的合规性：\\n" + segment.getContent())
                .build()
        );
        
        CompletableFuture<ChatCompletionResponse> response;
        
        if (segmentImages != null && !segmentImages.isEmpty()) {
            // 使用VLM检查视觉合规要素（印章、签名等）
            response = siliconFlowClient.chatCompletionVLM(
                messages, 
                segmentImages, 
                ChatCompletionRequest.builder()
                    .temperature(0.1)
                    .maxTokens(2000)
            );
        } else {
            // 使用LLM检查文本合规要素
            response = siliconFlowClient.chatCompletionLLM(
                messages, 
                ChatCompletionRequest.builder()
                    .temperature(0.1)
                    .maxTokens(2000)
            );
        }
        
        return response.thenApply(this::parseComplianceResult);
    }
    
    /**
     * 自然语言问答
     * 支持用户与AI交互，解答处理相关问题
     */
    public CompletableFuture<String> naturalLanguageQuery(
            String query, 
            Map<String, Object> context) {
        
        String contextPrompt = promptLibrary.getNLQueryPrompt();
        String contextInfo = buildContextInfo(context);
        
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("system")
                .content(contextPrompt)
                .build(),
            Message.builder()
                .role("user")
                .content("上下文信息：\\n" + contextInfo + "\\n\\n用户问题：" + query)
                .build()
        );
        
        return siliconFlowClient.chatCompletionLLM(
            messages, 
            ChatCompletionRequest.builder()
                .temperature(0.3)
                .maxTokens(1500)
        ).thenApply(response -> response.getFirstChoiceContent());
    }
    
    /**
     * 批量文档处理
     * 支持大规模文档的AI增强处理
     */
    public CompletableFuture<List<DocumentAnalysisResult>> batchProcessDocuments(
            List<CaseDocument> documents, 
            String processingType) {
        
        List<CompletableFuture<DocumentAnalysisResult>> futures = new ArrayList<>();
        
        for (CaseDocument doc : documents) {
            CompletableFuture<DocumentAnalysisResult> future = 
                siliconFlowClient.analyzeDocument(
                    doc.getContent(), 
                    doc.getImageUrls(), 
                    processingType
                );
            futures.add(future);
        }
        
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                    .map(CompletableFuture::join)
                    .collect(java.util.stream.Collectors.toList()));
    }
    
    // ============ 私有辅助方法 ============
    
    /**
     * 分析文档视觉结构
     */
    private CompletableFuture<DocumentAnalysisResult> analyzeDocumentStructure(
            CaseDocument caseDocument, 
            List<String> documentImages) {
        
        return siliconFlowClient.analyzeDocument(
            caseDocument.getContent(), 
            documentImages, 
            "structure_analysis"
        );
    }
    
    /**
     * 分析文档语义结构
     */
    private CompletableFuture<DocumentAnalysisResult> analyzeDocumentSemantics(
            CaseDocument caseDocument) {
        
        return siliconFlowClient.analyzeDocument(
            caseDocument.getContent(), 
            null, 
            "semantic_structure"
        );
    }
    
    /**
     * 生成分割策略
     */
    private CompletableFuture<List<DocumentSegment>> generateSplitStrategy(
            CaseDocument caseDocument, 
            DocumentAnalysisResult vision, 
            DocumentAnalysisResult semantic) {
        
        // 这里会根据AI分析结果生成分割策略
        // 实际实现中会有更复杂的算法
        return CompletableFuture.completedFuture(new ArrayList<>());
    }
    
    /**
     * 解析分类结果
     */
    private DocumentType parseClassificationResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        
        // 简单的关键词匹配，实际中会更复杂
        if (content.contains("处罚决定书")) {
            return DocumentType.CASE_DECISION;
        } else if (content.contains("告知书")) {
            return DocumentType.NOTICE;
        } else if (content.contains("证据清单")) {
            return DocumentType.EVIDENCE_LIST;
        } else if (content.contains("调查笔录")) {
            return DocumentType.INVESTIGATION_RECORD;
        }
        
        return DocumentType.OTHER;
    }
    
    /**
     * 解析合规性检查结果
     */
    private DocumentAnalysisResult parseComplianceResult(ChatCompletionResponse response) {
        String content = response.getFirstChoiceContent();
        
        return DocumentAnalysisResult.builder()
            .analysisType("compliance_check")
            .rawContent(content)
            .confidence(0.8)
            .build();
    }
    
    /**
     * 构建上下文信息
     */
    private String buildContextInfo(Map<String, Object> context) {
        StringBuilder sb = new StringBuilder();
        
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\\n");
        }
        
        return sb.toString();
    }
    
    /**
     * 设置服务配置
     */
    public void setConfig(String key, Object value) {
        serviceConfig.put(key, value);
    }
    
    /**
     * 获取服务配置
     */
    public Object getConfig(String key) {
        return serviceConfig.get(key);
    }
    
    /**
     * 健康检查
     */
    public CompletableFuture<Boolean> healthCheck() {
        List<Message> messages = Arrays.asList(
            Message.builder()
                .role("user")
                .content("健康检查")
                .build()
        );
        
        return siliconFlowClient.chatCompletionLLM(
            messages, 
            ChatCompletionRequest.builder()
                .temperature(0.0)
                .maxTokens(10)
        ).thenApply(response -> response.getFirstChoiceContent() != null)
        .orTimeout(10, TimeUnit.SECONDS)
        .exceptionally(throwable -> false);
    }
}